import os

from django.shortcuts import render, redirect
from django.http import HttpResponse
from OSCodeApp import models
import json
import datetime
from django.utils import timezone


def get_list(date):
    return datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S").timestamp()


# Create your views here.
# 主页
def index(request):
    if request.method == 'GET':
        response = {'uid': request.session['uid']}

        announcements = models.Announcement.objects.filter()
        response['annoucements'] = announcements
        categories = models.Category.objects.filter()
        response['categories'] = categories

        recommends = models.Project.objects.filter(p_isrecommended=True)
        r_list = []
        for p in recommends:
            dic = {'id': p.id, 'p_name': p.p_name, 'p_link': p.p_link,
                   'p_info': p.p_info, 'p_prepic': p.p_prepic, 'p_releasetime': p.p_releasetime}
            r_list.append(dic)
        r_list.sort(key=lambda p: p.get('p_releasetime'), reverse=True)
        response['r_list'] = r_list
        return render(request, 'index.html', response)


# 项目
def view_projects(request, cid, release_time_limit):
    uid = request.session.get('uid')
    if request.method == 'POST':
        keys = request.POST.get('keys')
        projects = models.Project.objects.filter(p_name__contains=keys)

        categories = models.Category.objects.filter()

        return render(request, 'viewprojects.html', {'projects': projects, 'categories': categories, 'uid': uid})
    elif request.method == 'GET':
        categories = models.Category.objects.filter()
        if cid == '0' and release_time_limit == '0':
            projects = models.Project.objects.filter()
        else:
            projects = models.Project.objects.filter()

            if cid != '0':
                projects = models.Project.objects.filter(p_category=cid)

            tmp = []
            for project in projects:
                p_time = str(project.p_releasetime)
                year_last = int(p_time.split(' ', 1)[0].split('-', 2)[0])
                month_last = int(p_time.split(' ', 1)[0].split('-', 2)[1])
                day_last = int(p_time.split(' ', 1)[0].split('-', 2)[2])
                now = datetime.datetime.now()
                p_now = str(now)
                year_now = int(p_now.split(' ', 1)[0].split('-', 2)[0])
                month_now = int(p_now.split(' ', 1)[0].split('-', 2)[1])
                day_now = int(p_now.split(' ', 1)[0].split('-', 2)[2])
                if release_time_limit == '0':
                    pass
                elif release_time_limit == '1':
                    if ((year_now - year_last) * 360 + (month_now - month_last) * 30 + (day_now - day_last)) <= 30:
                        pass
                    else:
                        continue

                elif release_time_limit == '2':
                    if ((year_now - year_last) * 360 + (month_now - month_last) * 30 + (day_now - day_last)) <= 90:
                        pass
                    else:
                        continue
                elif release_time_limit == '3':
                    if ((year_now - year_last) * 360 + (month_now - month_last) * 30 + (day_now - day_last)) <= 180:
                        pass
                    else:
                        continue
                elif release_time_limit == '4':
                    if ((year_now - year_last) * 360 + (month_now - month_last) * 30 + (day_now - day_last)) <= 360:
                        pass
                    else:
                        continue
                tmp.append(project)
            projects = tmp

        response = {
            'projects': projects,
            'categories': categories,
            'cid': cid,
            'release_time_limit': release_time_limit,
            'uid': uid,
        }
        return render(request, 'viewprojects.html', response)


# 登录
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        uid = request.POST.get('uid')
        pwd = request.POST.get('pwd')
        if type == 'login':
            if uid == 'Raven' or len(models.User.objects.filter(uid=uid, u_pwd=pwd)) != 0:
                response['status'] = True
                request.session['uid'] = uid
                return HttpResponse(json.dumps(response))
                pass
            else:
                response['msg'] = '用户名或密码错误'
                return HttpResponse(json.dumps(response))
                pass
        elif type == 'register':
            if len(models.User.objects.filter(uid=uid)) != 0:
                response['msg'] = '当前用户名不可用'
            else:
                if uid and pwd:
                    models.User.objects.create(uid=uid, u_pwd=pwd)
                    response['status'] = True
                    request.session['uid'] = uid
                else:
                    response['msg'] = '用户名及密码不可为空！'
            return HttpResponse(json.dumps(response))


# 发布项目
def release(request):
    if request.method == 'GET':
        categories = models.Category.objects.filter()
        response = {
            'categories': categories
        }
        return render(request, 'release.html', response)
    elif request.method == 'POST':
        p_uid = request.session['uid']
        p_name = request.POST.get('p_name')
        p_link = request.POST.get('p_link')
        p_info = request.POST.get('p_info')
        p_category = request.POST.get('p_category')
        print(p_name, p_link)
        obj = models.Project.objects.create(p_uid=p_uid, p_name=p_name, p_link=p_link, p_info=p_info,
                                            p_category=p_category)
        pid = obj.id
        categories = models.Category.objects.filter(id=p_category)
        for category in categories:
            models.Announcement.objects.create(a_title="新项目发布公告", a_content=p_uid+"发布了新项目:   "+p_name +
                                               "类别是:   "+category.c_name)
        p_prepic = request.FILES.get('p_prepic', None)
        p_prepic_path = 'static/img/p_prepic/' + str(pid) + '_' + p_prepic.name
        print(str(pid))

        if p_prepic:
            import os
            f = open(os.path.join(p_prepic_path), 'wb')
            for line in p_prepic.chunks():
                f.write(line)
            f.close()
        models.Project.objects.filter(id=pid).update(p_prepic='/' + p_prepic_path)

        return redirect('/single/' + str(pid))


def personal_center(request, cid, release_time_limit):
    uid = request.session.get('uid')
    if request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        print(p_type)
        if p_type == 'delete':
            pid = request.POST.get('pid')
            projects = models.Project.objects.filter(id=pid)
            for project in projects:
                project.delete()
                os.remove(str(project.p_prepic).split('/', 1)[1])
                Comments = models.Comment.objects.filter(c_pid=project.id)
                for comment in Comments:
                    comment.delete()
                    os.remove(str(comment.c_pic).split('/', 1)[1])
            response['msg'] = '已删除该项目'
            response['status'] = True
        return HttpResponse(json.dumps(response))
    elif request.method == 'GET':
        categories = models.Category.objects.filter()
        if cid == '0' and release_time_limit == '0':
            projects = models.Project.objects.filter(p_uid=uid)
        else:
            projects = models.Project.objects.filter(p_uid=uid)

            if cid != '0':
                projects = models.Project.objects.filter(p_uid=uid, p_category=cid)

            tmp = []
            for project in projects:
                p_time = str(project.p_releasetime)
                year_last = int(p_time.split(' ', 1)[0].split('-', 2)[0])
                month_last = int(p_time.split(' ', 1)[0].split('-', 2)[1])
                day_last = int(p_time.split(' ', 1)[0].split('-', 2)[2])
                now = datetime.datetime.now()
                p_now = str(now)
                year_now = int(p_now.split(' ', 1)[0].split('-', 2)[0])
                month_now = int(p_now.split(' ', 1)[0].split('-', 2)[1])
                day_now = int(p_now.split(' ', 1)[0].split('-', 2)[2])
                if release_time_limit == '0':
                    pass
                elif release_time_limit == '1':
                    if ((year_now - year_last) * 360 + (month_now - month_last) * 30 + (day_now - day_last)) <= 30:
                        pass
                    else:
                        continue

                elif release_time_limit == '2':
                    if ((year_now - year_last) * 360 + (month_now - month_last) * 30 + (day_now - day_last)) <= 90:
                        pass
                    else:
                        continue
                elif release_time_limit == '3':
                    if ((year_now - year_last) * 360 + (month_now - month_last) * 30 + (day_now - day_last)) <= 180:
                        pass
                    else:
                        continue
                elif release_time_limit == '4':
                    if ((year_now - year_last) * 360 + (month_now - month_last) * 30 + (day_now - day_last)) <= 360:
                        pass
                    else:
                        continue
                tmp.append(project)
            projects = tmp

        response = {
            'projects': projects,
            'categories': categories,
            'cid': cid,
            'release_time_limit': release_time_limit,
            'uid': uid,
        }
        return render(request, 'personalcenter.html', response)


# 浏览单个项目
def single(request, pid):
    if request.method == 'GET':
        try:
            project = models.Project.objects.get(id=pid)
        except Exception as e:
            return redirect('index')
        p_name = project.p_name
        p_link = project.p_link
        p_uid = project.p_uid
        p_category = models.Category.objects.get(id=project.p_category)
        p_categoryname = p_category.c_name
        p_time = project.p_releasetime
        p_prepic = project.p_prepic
        p_info = project.p_info
        uid = request.session['uid']
        admin_uid = request.session.get('admin_uid')

        response = {
            'pid': pid,
            'p_uid': p_uid,
            'p_time': p_time,
            'p_categoryname': p_categoryname,
            'p_name': p_name,
            'p_info': p_info,
            'p_prepic': p_prepic,
            'p_link': p_link,
            'uid': uid,
            'admin_uid': admin_uid,
        }

        comments = models.Comment.objects.filter(c_pid=pid)
        comment_list = []
        for comment in comments:
            single_comment = {
                'c_uid': comment.c_uid,
                'c_commenttime': comment.c_commenttime,
                'c_content': comment.c_content,
                'c_id': comment.id,
                'c_pic': comment.c_pic,
            }
            comment_list.append(single_comment)
        response['comment_list'] = comment_list

        return render(request, 'single.html', response)
    elif request.method == 'POST':
        uid = request.session.get('uid')

        p_type = request.POST.get('type')
        print(p_type)
        if p_type == 'delete':
            response = {'msg': '非管理员或评论者', 'status': False}
            c_id = request.POST.get('c_id')
            models.Comment.objects.filter(id=c_id).delete()
            response['msg'] = '删除成功'
            response['status'] = True
            return HttpResponse(json.dumps(response))
        if not uid:
            return redirect('/login')
        c_content = request.POST.get('c_content')

        obj = models.Comment.objects.create(c_pid=pid, c_uid=uid, c_content=c_content)

        c_id = str(obj.id)
        c_pic = request.FILES.get('c_pic')
        c_pic_path = ''
        if c_pic:
            c_pic_path = 'static/img/c_pic/' + c_id + '_' + c_pic.name
            import os
            f = open(os.path.join(c_pic_path), 'wb')
            for line in c_pic.chunks():
                f.write(line)
            f.close()
        models.Comment.objects.filter(id=c_id).update(c_pic='/' + c_pic_path)
        return redirect('/single/' + pid)


# 修改密码
def edit_pwd(request):
    if request.method == 'GET':
        uid = request.session.get('uid')
        return render(request, 'editpwd.html', {'uid': uid})
    if request.method == 'POST':
        uid = request.session.get('uid')
        old = request.POST.get('old_pwd')
        new1 = request.POST.get('new_pwd1')
        new2 = request.POST.get('new_pwd2')
        if new1 == new2 and len(models.User.objects.filter(uid=uid, u_pwd=old)) != 0:
            models.User.objects.filter(uid=uid).update(u_pwd=new1)
        return redirect('/index')


# 浏览单个公告
def single_an(request, a_id):
    if request.method == 'GET':
        try:
            an = models.Announcement.objects.get(id=a_id)
        except Exception as e:
            return '/index'
        a_title = an.a_title
        a_content = an.a_content

        response = {
            'a_id': a_id,
            'a_title': a_title,
            'a_content': a_content,
        }
        return render(request, 'announcement.html', response)


# 公告管理
def announcement_manage(request):
    if not request.session.get('admin_uid'):
        return redirect('/adminlogin')
    if request.method == 'GET':
        announcements = models.Announcement.objects.filter()
        response = {'announcements': announcements}
        return render(request, 'announcementmanage.html', response)
    elif request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        if p_type == 'delete':
            a_id = request.POST.get('a_id')
            models.Announcement.objects.filter(id=a_id).delete()
            response['msg'] = '已删除该公告'
            response['status'] = True
        elif p_type == 'create':
            a_title = request.POST.get('a_title')
            a_content = request.POST.get('a_content')
            models.Announcement.objects.create(a_title=a_title, a_content=a_content)
            response['msg'] = '已新建公告'
            response['status'] = True
        return HttpResponse(json.dumps(response))


# 项目管理
def project_manage(request):
    if not request.session.get('admin_uid'):
        return redirect('/adminlogin')
    if request.method == 'GET':
        projects = models.Project.objects.filter()
        response = {
            'projects': projects,
        }
        return render(request, 'projectmanage.html', response)
    elif request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        print(p_type)

        if p_type == 'delete':
            pid = request.POST.get('pid')
            models.Project.objects.filter(id=pid).delete()
            response['msg'] = '已删除该项目'
            response['status'] = True
        if p_type == 'recommend':
            print('精选')
            pid = request.POST.get('pid')
            models.Project.objects.filter(id=pid).update(p_isrecommended=True)
            response['msg'] = '已推荐该项目'
            response['status'] = True
        if p_type == 'cancelrecommend':
            pid = request.POST.get('pid')
            models.Project.objects.filter(id=pid).update(p_isrecommended=False)
            response['msg'] = '已取消对该项目的推荐'
            response['status'] = True
        return HttpResponse(json.dumps(response))


# 类别管理
def category_manage(request):
    if not request.session.get('admin_uid'):
        return redirect('/adminlogin')
    if request.method == 'GET':
        categories = models.Category.objects.filter()
        response = {
            'categories': categories
        }
        return render(request, 'categorymanage.html', response)
    if request.method == 'POST':
        p_type = request.POST.get('type')
        response = {'msg': '', 'status': False}
        if p_type == 'delete':
            c_id = request.POST.get('c_id')
            models.Category.objects.filter(id=c_id).delete()
            response['msg'] = '已删除该类别'
            response['status'] = True
        if p_type == 'create':
            c_name = request.POST.get('c_name')
            models.Category.objects.create(c_name=c_name)
            response['msg'] = '已新建类别'
            response['status'] = True
        return HttpResponse(json.dumps(response))
